package linkedlist;

public class MergeTwoLists {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val,ListNode next) {
            this.val = val;
            this.next = next;
        }

        public static void printList(ListNode head){
            while(head!=null){
                System.out.print(head.val + "->");
                head = head.next;
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        ListNode listNodeL3 = new ListNode(4,null);
        ListNode listNodeL2 = new ListNode(2,listNodeL3);
        ListNode listNodeL1 = new ListNode(1,listNodeL2);

        ListNode listNodeR3 = new ListNode(4,null);
        ListNode listNodeR2 = new ListNode(3,listNodeR3);
        ListNode listNodeR1 = new ListNode(1,listNodeR2);

        MergeTwoLists mergeTwoLists = new MergeTwoLists();
        mergeTwoLists.mergeTwoLists(listNodeL1,listNodeR1);
    }
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode head = new ListNode(-1);
        ListNode prev = head;
        while (list1 != null && list2 !=null) {
            if (list1.val > list2.val) {
                prev.next = list2;
                list2 = list2.next;
            } else {
                prev.next = list1;
                list1 = list1.next;
            }
            prev = prev.next;
        }
        prev.next = list1==null ?list2:list1;
        return head.next;
    }
}
